{% extends '_base.html' %}

{% block top_css %}
    {{ super() }}
    <!--Select2-->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='plugins/select2/css/select2.min.css') }}">
    <!--Daterangepicker-->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='plugins/daterangepicker/daterangepicker.css') }}">
    <!--bootstrap-table-->
    <link href="{{ url_for('static', filename='plugins/bootstrap-table/bootstrap-table.min.css') }}" rel="stylesheet">

    <!-- zTree -->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='plugins/zTree/css/awesomeStyle/awesome.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='plugins/bootstrap-submenu/css/bootstrap-submenu.css') }}">
    <!-- dropzone -->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='plugins/dropzone/dropzone.css') }}">

    <!--bees-->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bees.css') }}">

    <style>

        .ztree li span.button.roots_open::before,
        .ztree li span.button.center_open::before,
        .ztree li span.button.bottom_open::before,
        .ztree li span.button.root_open::before {
            content: "\f0d7";
            font-size: 15px;
        }

        .ztree li span.button.roots_close::before,
        .ztree li span.button.center_close::before,
        .ztree li span.button.bottom_close::before,
        .ztree li span.button.root_close::before {
            content: "\f0da";
            font-size: 15px;
        }

        .ztree li span.button.ico_docu::before {
            content: "\f15c";
        }

        .fa-icon {
            width: 15px;
        }

        .box {
            padding: 6px 10px 10px 10px;
        }

        .box .title {
            background-color: #FAFAFA;
            border-bottom: 1px solid #cccccc4a;
            font-size: 13px;
            height: 25px;
            line-height: 25px;
        }

        .box .tools {
            height: 28px;
            line-height: 28px;
            background-color: #fff;
            border-bottom: 1px solid #cccccc2b;
            margin-bottom: 5px;
        }

        .box .tools > a {
            margin: 5px;
        }

        .box .fixed-fluid {
            height: 75vh;
        }

        .box .fixed-sm-200 {
            height: 100%;
            position: relative;
        }

        .box .fixed-sm-200 .treebox {
            height: 100%;
            overflow: auto;
        }

        .box .fixed-sm-200 #rMenu {
            position: absolute;
            left: 0;
            top: 0;
            cursor: pointer;
        }

        .box .fluid {
            height: 100%;
        }

        .box .fluid .tab-base{
            height: 100%;
        }

        .box .fluid .tab-base .nav-tabs {
            background-color: #cccccc17;
            border-radius: 5px;
        }

        .box .fluid .tab-base .nav-tabs > li:not(.active) > a {
            color: #4d627b !important;
            background-color: #fff;
        }

        .box .fluid .tab-base .nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus {
            background-color: #EFEFEF !important;
            transition: background-color, 0.3s;
        }

        .box .fluid .nav>li>a {
            padding: 2px 8px !important;
        }

        .box .fluid .nav>li>a>.close{
            display: inline-block;
            margin-left: 12px;
            font-size: 12px;
            padding-top: 4px;
        }

        .box .fluid .tab-content {
            height: 100%;
            padding: 2px 0px !important;
            background-color: #EFEFEF;
        }

        .box .fluid .tab-content .tab-pane{
            height: 100%;
        }

        .file-upload {
            mix-height: 198px;
            width: 430px;
            background-color: #fff;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 4001;
            box-shadow: 0 1px 30px rgba(0, 0, 0, 0.6);
            display: none;
        }

        .file-upload .title {
            padding: 0 5px;
            height: 28px;
            line-height: 28px;
            background-color: #1a2b3c;
            font-size: 12px;
        }

        .file-upload .dropbox {
            padding: 10px;
            min-height: 170px;
            box-sizing: border-box;
        }

        .dropzone, .dropzone-container {
            padding: 10px;
        }

        .dropzone .dz-message,
        .dropzone-container .dz-message {
            margin: 0 !important;
        }

        .dropzone .dz-preview,
        .dropzone-container .dz-preview {
            margin: 0 4px 8px;
        }
    </style>

{% endblock %}


{% block content %}
    <div id="content-container">
        <!--头部-->
        <div id="page-head">
            <!--头部标题-->
            <div id="page-title">
                <h1 class="page-header text-overflow">{% block head_title %}{% endblock %}</h1>
            </div>
            <!--导航标题-->
            {% block head_nav %}
            {% endblock %}
        </div>

        <!--内容-->
        <div id="page-content">
            <div class="panel">
                <div class="box">
                    <div class="title">
                        <span>测试</span>
                    </div>
                    <div class="tools">
                        <a href="#" title="保存" id="save"><i class="fa fa-icon fa-save" aria-hidden="true"></i></a>
                        <a href="#" title="复制" id="copy"><i class="fa fa-icon fa-copy" aria-hidden="true"></i></a>
                        <a href="#" title="剪切" id="cut"><i class="fa fa-icon fa-cut" aria-hidden="true"></i></a>
                        <a href="#" title="粘贴" id="paste"><i class="fa fa-icon fa-paste" aria-hidden="true"></i></a>
                    </div>
                    <div class="fixed-fluid">
                        <div class="fixed-sm-200 pull-sm-left fixed-right-border">
                            <div class="treebox">
                                <div id="nTree" class="ztree">
                                </div>
                                <div id="fUpload" class="file-upload">
                                    <div class="title">
                                        <span class="pull-left">上传文件 - 目录名称</span>
                                        <span class="pull-right" onclick="closeUploadDialog();"><a href="#"><i class="fa fa-close" aria-hidden="true"></i></a></span>
                                    </div>
                                    <div class="dropbox">
                                        <div id="fileDropzone" class="dropzone dz-clickable">
                                            <div class="dz-default dz-message">
                                                <div class="dz-icon">
                                                    <i class="fa fa-cloud-upload fa-5x"></i>
                                                </div>
                                                <div>
                                                    <span class="dz-text">请把文件拖拽到此或者点击此区域</span>
                                                    <p class="text-sm text-muted">支持的文件类型.sh,.yml,.j2,.conf,.md,.gzip,.gz,.zip,bz2</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="rMenu">
                                    <ul class="dropdown-menu">
                                        <li class="dropdown-submenu">
                                          <a tabindex="0"><i class="fa fa-plus"></i> 新建</a>
                                          <ul class="dropdown-menu">
                                            <li id="m_create_dir" onclick="addTreeNode(type='dir');"><a tabindex="0"><i class="fa fa-icon fa-folder"></i> 目录 </a></li>
                                            <li id="m_create_file" onclick="addTreeNode(type='file');"><a tabindex="0"><i class="fa fa-icon fa-file"></i> 文件 </a></li>
                                          </ul>
                                        </li>
                                        <li id="m_update" onclick="editTreeNode();"><a tabindex="0"><i class="fa fa-icon fa-edit"></i> 重命名 </a></li>
                                        <li id="m_delete" onclick="removeTreeNode();"><a tabindex="0"><i class="fa fa-icon fa-minus"></i> 删除 </a></li>
                                        <li class="divider"></li>
                                        <li id="m_copy" onclick="copyTreeNode();"><a tabindex="0"><i class="fa fa-icon fa-copy"></i> 复制 </a></li>
                                        <li id="m_cut" onclick="cutTreeNode();"><a tabindex="0"><i class="fa fa-icon fa-cut"></i> 剪切 </a></li>
                                        <li id="m_paste" onclick="pasteTreeNode();"><a tabindex="0"><i class="fa fa-icon fa-paste"></i> 粘贴 </a></li>
                                        <li class="divider"></li>
                                        <li id="m_upload" onclick="openUploadDialog();"><a tabindex="0"><i class="fa fa-icon fa-upload"></i> 上传文件 </a></li>
                                    </ul>
                                </div>
                        </div>
                        <div class="fluid">
                            <div class="tab-base">
                                <!--Nav tabs-->
                                <ul class="nav nav-tabs">
{#                                    <li class="active">#}
{#                                        <a class="" data-toggle="tab" href="#ico-lft-tab-1" aria-expanded="true">#}
{#                                            <span>test.yml</span>#}
{#                                            <span class="close"> <i class="fa fa-close" aria-hidden="true"></i></span>#}
{#                                        </a>#}
{#                                    </li>#}
                                </ul>
                                <!--Tabs Content-->
                                <div class="tab-content">
{#                                    <div id="ico-lft-tab-1" class="tab-pane fade active in">#}
{#                                        <div class="fs-box">#}
{#                                            <div class="label label-default">#}
{#                                                <i class="fs-max fa fa-expand"></i>#}
{#                                                <i class="fs-min fa fa-compress hidden"></i>#}
{#                                            </div>#}
{#                                            <div id="editor01" class="form-control" style="height: 520px; width: 100%"></div>#}
{#                                        </div>#}
{#                                    </div>#}

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}


{% block buttom_js %}
    {{ super() }}
    <!--Select2-->
    <script src="{{ url_for('static', filename='plugins/select2/js/select2.full.min.js') }}"></script>
    <script src="{{ url_for('static', filename='plugins/select2/js/i18n/zh-CN.js') }}"></script>
    <!--Daterangepicker-->
    <script src="{{ url_for('static', filename='plugins/daterangepicker/moment-with-locales.min.js') }}"></script>
    <script src="{{ url_for('static', filename='plugins/daterangepicker/daterangepicker.js') }}"></script>
    <!--Bootbox Modals-->
    <script src="{{ url_for('static', filename='plugins/bootbox/bootbox.min.js') }}"></script>
    <!--bootstrap-table-->
    <script src="{{ url_for('static', filename='plugins/bootstrap-table/bootstrap-table.min.js') }}"></script>
    <script src="{{ url_for('static', filename='plugins/bootstrap-table/locale/bootstrap-table-zh-CN.js') }}"></script>
    <!--jquery-cookie-->
    <script src="{{ url_for('static', filename='plugins/jquery-cookie/jquery.cookie.js') }}"></script>

    <!--引入JavaScript-->
    <!--jQuery [ REQUIRED ]-->
    <script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
    <!--BootstrapJS [ RECOMMENDED ]-->
    <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
    <!--NiftyJS [ RECOMMENDED ]-->
    <script src="{{ url_for('static', filename='js/nifty.js') }}"></script>
    <!--CsrfJS-->
    <script src="{{ url_for('static', filename='js/csrf.js') }}"></script>
    <!--zTree-->
    <script src="{{ url_for('static', filename='plugins/zTree/js/jquery.ztree.all.js') }}"></script>
    <script src="{{ url_for('static', filename='plugins/bootstrap-submenu/js/bootstrap-submenu.js') }}"></script>
    <!--ace-->
    <script type="text/javascript" src="{{ url_for('static', filename='plugins/ace/ace.js') }}"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='plugins/ace/ext-language_tools.js') }}"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='plugins/ace/theme-tomorrow.js') }}"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='plugins/ace/mode-yaml.js') }}"></script>
    <!-- dropzone -->
    <script type="text/javascript" src="{{ url_for('static', filename='plugins/dropzone/dropzone.js') }}"></script>
    <!--bees-->
    <script src="{{ url_for('static', filename='js/bees.js') }}"></script>

    <script type="text/javascript">
		var zTree, rMenu = null;
        var showMenu = false;
        var fDropzone = null;

        function initNodeTree(options) {
            var treeUrl = '{{ url_for('tasks.api-node-tree') }}?role_id={{ id }}';
            var setting = {
                view: {
                    dblClickExpand: true,
                    showLine: true
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                async: {
                    enable: true,  // 异步加载菜单
                    url: treeUrl,
                    autoParam: ["id", "name", "parent"],
                    type: 'get'
                },
                edit: {
                    enable: true,
                    showRemoveBtn: false,
                    showRenameBtn: false,
                    drag: {
                        isCopy: true,
                        isMove: true
                    }
                },
                callback: {
                    onRightClick: onRightClick,
                    beforeClick: beforeClick,
                    onRename: onRename,
                    onSelected: onSelected,
                    onDblClick: onDblClick,
                    beforeDrag: beforeDrag,
                    onDrag: onDrag,
                    beforeDrop: beforeDrop,
                    onDrop: onDrop,
                    beforeAsync: defaultCallback("Before async")
                }
            };

            $.get(treeUrl, function (data, status) {
                zTree = $.fn.zTree.init($("#nTree"), setting, data);
                if (options.showMenu) {
                    showMenu = true;
                    rMenu = $("#rMenu");
                }
            });
        }

        function onBodyMouseDown(event){
            if (!(event.target.id === "rMenu" || $(event.target).parents("#rMenu").length>0)) {
                rMenu.css({"visibility" : "hidden"});
            }
        }

        function showRMenu(type, x, y) {
            var offset = $("#nTree").offset();
            var scrollTop = document.querySelector('.treebox').scrollTop;
            x -= offset.left;
            y -= offset.top + scrollTop;
            x += document.body.scrollLeft;
            y += document.body.scrollTop + document.documentElement.scrollTop;
            rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});
            $("#rMenu > ul").show();
            $("body").bind("mousedown", onBodyMouseDown);
        }

        function hideRMenu() {
            if (rMenu) rMenu.css({"visibility": "hidden"});
            $("body").unbind("mousedown", onBodyMouseDown);
        }

        function onRightClick(event, treeId, treeNode) {
            if (!showMenu) {
                return
            }
            if (!treeNode && event.target.tagName.toLowerCase() !== "button" && $(event.target).parents("a").length === 0) {
                zTree.cancelSelectedNode();
                showRMenu("root", event.clientX, event.clientY);
            } else if (treeNode && !treeNode.noR) {
                zTree.selectNode(treeNode);
                showRMenu("node", event.clientX, event.clientY);
            }
        }

        function addTreeNode(type) {
            hideRMenu();
            var parentNode = zTree.getSelectedNodes()[0];
            if (!parentNode){
                return
            }
            zTree.expandNode(parentNode, true, null, null); // 打开节点

            var current_node = parentNode.meta.node.current;
            var url = "{{ url_for('tasks.api-node-add-children', pk=id) }}?node_id="+current_node;
            setAjaxCSRFToken();
            $.post(url, {type: type}, function (results){
                if (results.code === 200) {
                    var newNode = {
                        id: results.data.meta.node["key"],
                        name: results.data.meta.node["value"],
                        pId: parentNode.id,
                        current: results.data.meta.node["current"],
                        parent: results.data.meta.node["parent"],
                        isParent: results.data.isParent,
                        meta: {
                            "node": results.data.meta.node
                        }
                    };
                    newNode.checked = zTree.getSelectedNodes()[0].checked;

                    zTree.addNodes(parentNode, -1, newNode); // 新增节点
                    var node = zTree.getNodeByParam('id', newNode.id, parentNode);
                    zTree.editName(node);

                    bees.tipSuccess({
                        message: '节点保存成功'
                    });
                } else {
                    if(results.data.message){
                        bees.tipError({
                            message: results.data.message
                        });
                    }else {
                        bees.tipError({
                            message: '节点保存失败'
                        });
                    }
                }
            });
        }

        function removeTreeNode() {
            hideRMenu();
            var current_node = zTree.getSelectedNodes()[0];
            if (!current_node){
                return
            }

            bees.confirmBox({
                title: '删除节点',
                content: "你想删除节点: " + current_node.name + " 吗?",
                confirmCallback: function () {
                    confirmRemoveTreeNode();
                },
                cancelCallback: function () {
                }
            });

            function confirmRemoveTreeNode() {
                var node_id = current_node.meta.node.current;
                var url = "{{ url_for('tasks.api-node-delete', pk=id) }}?node_id="+node_id+"";

                setAjaxCSRFToken();
                $.post(url, {}, function (results){
                    if (results.code === 200) {
                        zTree.removeNode(current_node);
                        fixIcon();
                        bees.tipSuccess({
                            message: '删除节点成功'
                        });
                    } else {
                        if(results.data.message){
                            bees.tipError({
                                message: results.data.message
                            });
                        }else {
                            bees.tipError({
                                message: '删除节点失败'
                            });
                        }
                    }
                });
            }

        }

        function editTreeNode() {
            hideRMenu();
            var current_node = zTree.getSelectedNodes()[0];
            if (!current_node){
                return
            }
            zTree.editName(current_node);
        }

        function onRename(event, treeId, treeNode, isCancel) {
            var node_id = treeNode.meta.node.key;
            var current_node = treeNode.meta.node.current;
            var url = "{{ url_for('tasks.api-node-rename', pk=id) }}?node_id="+current_node+"";
            var data = {"node_name": treeNode.name, "parent": treeNode.parent};
            if (isCancel){
                return
            }

            setAjaxCSRFToken();
            $.post(url, data, function (results){
                if (results.code === 200) {
                    treeNode.current = results.data.current;
                    treeNode.parent = results.data.parent;
                    treeNode.meta.node.value = results.data.meta.node.value;
                    treeNode.meta.node.current = results.data.meta.node.current;
                    treeNode.meta.node.parent = results.data.meta.node.parent;
                    zTree.updateNode(treeNode);
                    bees.tipSuccess({
                        message: '重命名节点成功'
                    });
                } else {
                    if(results.data.message){
                        bees.tipError({
                            message: results.data.message
                        });
                    }else {
                        bees.tipError({
                            message: '重命名节点失败'
                        });
                    }
                    var node = zTree.getNodeByParam('id', node_id);
                    zTree.editName(node);
                }
            });
        }

        function beforeDrop(treeId, treeNodes, targetNode, moveType) {
            if(!targetNode.isParent){
                bees.tipError({
                    message: '目标节点不是目录，无法移动！'
                });
                return false;
            }

            var treeNodesNames = [];
            $.each(treeNodes, function (index, value) {
                treeNodesNames.push(value.name);
            });

            var msg = "你想移动节点: `" + treeNodesNames.join(",") + "` 到 `" + targetNode.name + "` 下吗?";
            var flag = confirm(msg);
            return flag;

            var isConfirm = null;
            bees.confirmBox({
                title: '移动节点',
                content: "你想移动节点: `" + treeNodesNames.join(",") + "` 到 `" + targetNode.name + "` 下吗?",
                confirmCallback: function () {
                    isConfirm = true;
                },
                cancelCallback: function () {
                    isConfirm = false;
                }
            });
        }

        function fixIcon() {
            // 找到自己定义isParent的标识字段，进行ztreedom赋值
            var folderNode = zTree.getNodesByFilter(function (node) { return node.meta.node.isParent });
            // 遍历目录节点，设置isParent属性为true;
            for(var j=0 ; j<folderNode.length; j++){//遍历目录节点，设置isParent属性为true;
                folderNode[j].isParent = true;
            }
            // 调用api自带的refresh函数。
            zTree.refresh();
        }

        function onDrop(event, treeId, treeNodes, targetNode, moveType) {
            // 调用修复图标的方法
            fixIcon();

            // 获取需要移动的节点
            var sourceTreeNodes = [];
            $.each(treeNodes, function (index, value) {
                sourceTreeNodes.push(value.meta.node.current);
            });

            var targetTreeNode = targetNode.meta.node.current;
            var url = "{{ url_for('tasks.api-node-move-children', pk=id) }}?target_node="+targetTreeNode+"";
            var data = {source_nodes: JSON.stringify(sourceTreeNodes)};

            setAjaxCSRFToken();
            $.post(url, data, function (results){
                if (results.code === 200) {
                    zTree.updateNode(treeNodes);
                    bees.tipSuccess({
                        message: '移动节点成功'
                    });
                } else {
                    if(results.data.message){
                        bees.tipError({
                            message: results.data.message
                        });
                    }else {
                        bees.tipError({
                            message: '节点创建失败'
                        });
                    }
                }
            });
        }

        function onDblClick(event, treeIdString, treeNode) {
            if(treeNode.isParent){
                zTree.expandNode(treeNode, true);
            }else {
                var current_node = treeNode.meta.node.current;
                var url = "{{ url_for('tasks.api-node-file-content', pk=id) }}?node_id="+current_node+"";

                setAjaxCSRFToken();
                $.get(url, function (results){
                    if (results.code === 200) {
                        var tabs = $("ul.nav-tabs");
                        var editorId = tabs.addTabs({
                            "id": current_node,
                            "title": results.data.name,
                            "content": results.data.content
                        });
                        if(editorId){
                            initEditor(editorId);
                        }
                    } else {
                        if(results.data.message){
                            bees.tipError({
                                message: results.data.message
                            });
                        }else {
                            bees.tipError({
                                message: '获取文件内容失败'
                            });
                        }
                    }
                });
            }
        }

        function onSelected(event, treeNode) {
        }

        function beforeClick() {
            return true;
        }

        function beforeDrag() {
            return true
        }

        function onDrag() {
        }

        function defaultCallback(action) {
            function logging() {
                console.log(action)
            }
            return logging
        }

        // 复制和剪切
        var curSrcNode, curType;
        function fontCss(treeNode) {
			var aObj = $("#" + treeNode.tId + "_a");
			aObj.removeClass("copy").removeClass("cut");
			if (treeNode === curSrcNode) {
				if (curType == "copy") {
					aObj.addClass(curType);
				} else {
					aObj.addClass(curType);
				}
			}
		}
		function setCurSrcNode(treeNode) {
			if (curSrcNode) {
				delete curSrcNode.isCur;
				var tmpNode = curSrcNode;
				curSrcNode = null;
				fontCss(tmpNode);
			}
			curSrcNode = treeNode;
			if (!treeNode) return;

			curSrcNode.isCur = true;
			zTree.cancelSelectedNode();
			fontCss(curSrcNode);
		}
        function copyTreeNode() {
            hideRMenu();
			var nodes = zTree.getSelectedNodes();
			if (nodes.length == 0) {
				bees.tipError({
                    message: '请先选择一个节点'
                });
				return;
			}
			curType = "copy";
			setCurSrcNode(nodes[0]);
        }
        function cutTreeNode() {
            hideRMenu();
            var nodes = zTree.getSelectedNodes();
			if (nodes.length == 0) {
				bees.tipError({
                    message: '请先选择一个节点'
                });
				return;
			}
			curType = "cut";

			console.log(nodes[0]);

			setCurSrcNode(nodes[0]);
        }
        function pasteTreeNode() {
            hideRMenu();
            if (!curSrcNode) {
				bees.tipError({
                    message: '请先选择一个节点进行复制/剪切'
                });
				return;
			}
			var nodes = zTree.getSelectedNodes();
			var targetNode = nodes.length>0? nodes[0]:null;
			if (curSrcNode === targetNode) {
				bees.tipError({
                    message: '不能移动，源节点与目标节点相同'
                });
				return;
			} else if (curType === "cut" && ((!!targetNode && curSrcNode.parentTId === targetNode.tId) || (!targetNode && !curSrcNode.parentTId))) {
				bees.tipError({
                    message: '不能移动，源节点已经存在于目标节点中'
                });
				return;
			} else if (curType === "copy") {
			    var current_node = curSrcNode.meta.node.current;
                var url = "{{ url_for('tasks.api-node-copy', pk=id) }}?node_id="+current_node+"";
                setAjaxCSRFToken();
                $.post(url, {}, function (results){
                    if (results.code === 200) {
                        var parentNode = zTree.getNodeByParam('id', results.data.pId);
                        var newNode = {
                            id: results.data.meta.node["key"],
                            name: results.data.meta.node["value"],
                            pId: parentNode.id,
                            isParent: results.data.isParent,
                            meta: {
                                "node": results.data.meta.node
                            }
                        };
                        newNode.checked = zTree.getSelectedNodes()[0].checked;

                        zTree.addNodes(parentNode, -1, newNode); // 新增节点
                        var node = zTree.getNodeByParam('id', newNode.id, parentNode);
                        zTree.editName(node);

                        //targetNode = zTree.copyNode(targetNode, curSrcNode, "inner");
                        setCurSrcNode();
                        delete targetNode.isCur;
                        zTree.selectNode(targetNode);

                        bees.tipSuccess({
                            message: '节点复制成功'
                        });

                    } else {
                        if(results.data.message){
                            bees.tipError({
                                message: results.data.message
                            });
                        }else {
                            bees.tipError({
                                message: '节点创建失败'
                            });
                        }
                    }
                });
			} else if (curType === "cut") {
                // 获取需要移动的节点
                var curNodesIds = [];
                curNodesIds.push(curSrcNode.meta.node.id);
                var node_id = targetNode.meta.node.id;
                var url = "{{ url_for('tasks.api-node-move-children', pk=id) }}?node_id="+node_id+"";
                var data = {nodes: JSON.stringify(curNodesIds)};

                setAjaxCSRFToken();
                $.post(url, data, function (results){
                    if (results.code === 200) {
                        // 前端实现移动
                        zTree.moveNode(targetNode, curSrcNode, "inner");
				        targetNode = curSrcNode;
				        setCurSrcNode();
                        delete targetNode.isCur;
                        zTree.selectNode(targetNode);
                        // 调用修复图标的方法
                        fixIcon();

                        bees.tipSuccess({
                            message: '移动节点成功'
                        });
                    } else {
                        if(results.data.message){
                            bees.tipError({
                                message: results.data.message
                            });
                        }else {
                            bees.tipError({
                                message: '移动节点失败'
                            });
                        }
                    }
                });
			}

        }

        //文件上传
        function openUploadDialog() {
            fDropzone.removeAllFiles();
            // 已经打开
            var display =$('#fUpload').css('display');
            if(display =='block'){
                return
            }

            hideRMenu();
            var nodes = zTree.getSelectedNodes();
            if(!nodes){
                return
            }
            if(!nodes[0].isParent) {
                bees.tipError({
                    message: '请选择文件需要上传的目录'
                });
                return
            }else {
                zTree.expandNode(nodes[0], true);
            }

            var title = nodes[0].name;
            $("#fUpload").find('.title > span').eq(0).text('文件上传-' + title);
            $("#fUpload").show();
        }

        function closeUploadDialog() {
            fDropzone.removeAllFiles();
            $("#fUpload").hide();
        }

        function uploadFile() {
            Dropzone.autoDiscover = false;
            var url = "{{ url_for('tasks.api-node-file-upload', pk=id) }}";
            var acceptedFiles = ['.sh', '.yml', '.conf', '.j2', '.md', '.gzip', '.gz', '.zip', 'bz2'];
            fDropzone = new Dropzone("#fileDropzone", {
                url: url,
                addRemoveLinks: false,
                method: 'post',
                filesizeBase: 1024,
                uploadMultiple: false,
                acceptedFiles: acceptedFiles.join(','),
                dictInvalidFileType: '上传文件类型不允许',
                addedfile: function (file) {
                    var fileArr = file.name.split('.');
                    var fileExt = '.' + fileArr[fileArr.length-1];
                    if($.inArray(fileExt.trim(), acceptedFiles) < 0){
                        bees.tipError({
                            message: '上传文件类型不允许'
                        });
                        return false
                    }
                },
                sending: function(file, xhr, formData) {
                    //向后台发送自定义的参数
                    var nodes = zTree.getSelectedNodes();
                    formData.append('current_node', nodes[0].current);
                    formData.append('node_id', nodes[0].id);
                    formData.append("filesize", file.size);
                    var csrftoken = $('meta[name=csrf-token]').attr('content');
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                },
                success: function (file, results) {
                     closeUploadDialog();
                    if (results.code === 200) {
                        var parentNode = zTree.getNodeByParam('id', results.data.pId);
                        var newNode = {
                            id: results.data.meta.node["key"],
                            name: results.data.meta.node["value"],
                            pId: results.data.pId,
                            isParent: results.data.isParent,
                            meta: {
                                "node": results.data.meta.node
                            }
                        };
                        newNode.checked = zTree.getSelectedNodes()[0].checked;

                        zTree.addNodes(parentNode, -1, newNode); // 新增节点

                        bees.tipSuccess({
                            message: '文件上传成功'
                        });
                    } else {
                        if(results.data.message){
                            bees.tipError({
                                message: results.data.message
                            });
                        }else {
                            bees.tipError({
                                message: '文件上传失败'
                            });
                        }
                    }
                },
                error: function (file, response, e) {
                }
            });
        }

        uploadFile();

        // editor
        var editors = {};
        function initEditor(ele) {
            // 代码编辑器初始化
            var id = ele.split('-')[1];
            $(document).ready(function () {
                ace.require("ace/ext/language_tools");
                editors[id] = ace.edit(ele);
                editors[id].setOptions({
                    enableBasicAutocompletion: true,
                    enableSnippets: true,
                    enableLiveAutocompletion: true //只能补全
                });
                editors[id].setTheme("ace/theme/tomorrow");//monokai模式是自动显示补全提示
                editors[id].getSession().setMode("ace/mode/yaml");//语言
                editors[id].setShowPrintMargin(false);
                editors[id].setFontSize(14)
            });

            // 代码编辑器
            $(".fs-box > .label").on('click', function () {
                $(this).parent('.fs-box').toggleClass('fullscreen');
                if($(this).parent('.fs-box').hasClass('fullscreen')){
                    $('.fs-box .fs-max').addClass('hidden');
                    $('.fs-box .fs-min').removeClass('hidden');
                    $(ele).css({'height':'100%'});
                    editors[id].resize();
                }else {
                    $('.fs-box .fs-min').addClass('hidden');
                    $('.fs-box .fs-max').removeClass('hidden');
                    $(ele).css({'height':'520px'});
                    editors[id].resize();
                }
            });
        }

        function initEditorOperator() {
             // 保存
            $("#save").on('click', function () {
                var current_node = $('.nav-tabs > li.active').attr('id').split('-')[0];
                var text = editors[current_node].getValue();

                var url = "{{ url_for('tasks.api-node-file-content', pk=id) }}?node_id="+current_node+"";
                setAjaxCSRFToken();
                $.post(url, {content: text}, function (results){
                    if (results.code === 200) {
                        bees.tipSuccess({
                            message: '数据修改成功'
                        });
                    } else {
                        if(results.data.message){
                            bees.tipError({
                                message: results.data.message
                            });
                        }else {
                            bees.tipError({
                                message: '数据创建失败'
                            });
                        }
                    }
                });
            });
        }

        // submenu
        function initSubMenu() {
            $('.dropdown-submenu > a').submenupicker();
            $('.dropdown-submenu').hover(function() {
                $(this).addClass('open');
                $(this).children('.dropdown-menu').css('display', 'block');
            }, function () {
                $(this).removeClass('open');
                $(this).children('.dropdown-menu').css('display', 'none');
            });
        }

        // addTabs
        function initTabsPlugin() {
            $.fn.addTabs = function (options) {
                //判断是否已存在指定ID的tab
                if ($("#" + options.id).length > 0) {
                    $('li[id='+options.id+'-li]').siblings().removeClass("active").removeClass("in");
                    $('li[id='+options.id+'-li]').addClass('active').addClass("in");
                    $('div[id='+options.id+']').siblings().removeClass("active").removeClass("in");
                    $('div[id='+options.id+']').addClass('active').addClass("in");
                    return null
                }

                //构建li元素
                var li = $("<li />", {
                    "id": options.id + "-li"
                });

                //构建a元素
                var a = $("<a />", {
                    "href": "#" + options.id,
                    "data-toggle": "tab"
                });

                var titleHtml  = '<span>'+options.title+'</span><span class="close"> <i class="fa fa-close" aria-hidden="true"></i></span>';
                a.html(titleHtml);

                //合并li和a元素
                li.append(a);

                var ul = $(this);
                //合并ul和li元素
                ul.append(li);

                //添加完成显示当前li
                $(li).tab("show");

                //构建div内容元素
                var div = $("<div />", {
                    "id": options.id,
                    "class": "tab-pane fade in active"
                });

                var editorId = options.title + '-' + options.id;
                var contentHtml =
                '<div class="fs-box">' +
                    '<div class="label label-default">' +
                        '<i class="fs-max fa fa-expand"></i>' +
                        '<i class="fs-min fa fa-compress hidden"></i>' +
                    '</div>' +
                    '<div id="'+ editorId +'" class="form-control" style="height: 100%; width: 100%">'+options.content+'</div>' +
                '</div>';
                div.html(contentHtml);

                var container = $(".tab-content");
                container.append(div);

                //添加完成后显示div
                $(div).siblings().removeClass("active");

                return editorId
            };
            //bindCloseEvent
            (function () {
                $('.nav-tabs').on('click', '.close', function () {
                    var activeId = $(".nav-tabs > li.active").children('a').attr('href').replace('#', '');
                    var currentId = $(this).closest('a').attr('href').replace('#', '');
                    // 激活的tab和点击的tab是同一个，需要处理
                    if(activeId == currentId){
                        // 先找前一个tab
                        var $targetLi = $(this).closest('li').prev();
                        // 在找后一个tab
                        if($targetLi.length == 0) {
                            $targetLi = $(this).closest('li').next();
                        }
                        // 只有一个tab处理
                        if($targetLi.length == 0) {
                            // 移除当前的tab
                            $('li[id="'+currentId+'-li"]').remove();
                            $('div[id="'+currentId+'"]').remove();
                        // 存在至少2个tab处理
                        }else {
                            // 激活相邻的tab
                            var targetId = $targetLi.children('a').attr('href').replace('#', '');
                            $('li[id="'+targetId+'-li"]').siblings().removeClass("active").removeClass("in");
                            $('li[id="'+targetId+'-li"]').addClass('active').addClass("in");
                            $('div[id="'+targetId+'"]').siblings().removeClass("active").removeClass("in");
                            $('div[id="'+targetId+'"]').addClass('active').addClass("in");

                            // 移除当前的tab
                            $('li[id="'+currentId+'-li"]').remove();
                            $('div[id="'+currentId+'"]').remove();
                        }
                    // 激活的tab和点击的tab不是同一个，直接移除点击的tab
                    }else {
                        $('li[id="'+currentId+'-li"]').remove();
                        $('div[id="'+currentId+'"]').remove();
                    }
                })
            })()
        }

        $(function () {
            initNodeTree({
                showMenu: true
            });
            initSubMenu();
            initTabsPlugin();

            initEditorOperator();
        });

	</script>

{% endblock %}

